const express = require('express');
const WebSocket = require('ws');
const os = require('os');
const path = require('path');
const cors = require('cors');

const app = express();
const port = 3000;
const number = 8;

// 启用 CORS
app.use(cors());

// WebSocket 服务器
const wss = new WebSocket.Server({ noServer: true });

// 用于存储所有连接的客户端
const clients = [];

// 评论数组，最多缓存100条
let all_comments = [];

// 最近一次请求的时间戳
let lastRequestTime = Date.now();

// 获取局域网IP地址的函数
function getLocalIPAddress() {
    const interfaces = os.networkInterfaces();
    let ipAddress = '';

    for (const interfaceName in interfaces) {
        for (const iface of interfaces[interfaceName]) {
            if (iface.family === 'IPv4' && !iface.internal) {
                ipAddress = iface.address;
                break;
            }
        }
    }

    return ipAddress;
}

// 监听 WebSocket 连接
wss.on('connection', (ws) => {
    clients.push(ws);

    ws.on('close', () => {
        const index = clients.indexOf(ws);
        if (index !== -1) {
            clients.splice(index, 1);
        }
    });
});

// 发送数据给所有连接的客户端
function sendDataToClients(data) {
    clients.forEach(client => {
        if (client.readyState === WebSocket.OPEN) {
            client.send(JSON.stringify(data));
        }
    });
}

// 定时器，每分钟检查是否超过10分钟未收到请求
setInterval(() => {
    const currentTime = Date.now();
    const timeDiff = currentTime - lastRequestTime; // 时间差，单位为毫秒
    if (timeDiff > 10 * 60 * 1000) { // 超过10分钟
        console.log('超过3分钟未收到请求，清空 all_comments');
        all_comments = []; // 清空评论数组
    }
}, 60 * 1000); // 每分钟检查一次

app.use(express.json());

// 函数：排序描述中的数字，若数字个数大于7则分组，每7个为一组，用括号括起来，并用空格连接
function matchAndSortNumbers(description) {
    const regex = /\d+((?:([^\w\u4e00-\u53f6\u53f8\u9fa5\d]+)|(?:号))(?:\d+))+|\d+/g; // 匹配多个数字或单个数字
    const matches = [...description.matchAll(regex)];

    matches.forEach(match => {
        const numberGroup = match[0].split(/[^0-9]+/).filter(num => num !== '');
        const sortedNumbers = numberGroup
            .map(Number)
            // .filter(num => num >= 1 && num <= 105)
            .sort((a, b) => a - b)
            .map(num => num.toString());

        const groupedNumbers = [];
        for (let i = 0; i < sortedNumbers.length; i += number) {
            if (sortedNumbers.length - i > number) {
                groupedNumbers.push(`(${sortedNumbers.slice(i, i + number).join(' ')})`);
                groupedNumbers.push("+");
            } else {
                groupedNumbers.push(sortedNumbers.slice(i).join(' '));
            }
        }

        description = description.replace(match[0], groupedNumbers.join(' '));
    });

    return description;
}

// POST 路径，用于接收评论数据
app.post('/api/comments', (req, res) => {
    lastRequestTime = Date.now(); // 更新最近请求时间

    const data = req.body.data;
    let comments = [];
    if (data) {
        if (data.comments) comments = data.comments;
        else if (data.comment_infos) comments = data.comment_infos;
    }

    if (comments.length > 0) {
        comments.forEach(comment => {
            const nick_name = comment.nick_name;
            let content = comment.content;

            if (nick_name && content) {
                content = matchAndSortNumbers(content);
                const commentObj = { nick_name, content };
                all_comments.push(commentObj);

                if (all_comments.length >= 100) {
                    all_comments.shift();
                }

                sendDataToClients({ comment: commentObj });
            }
        });
        res.status(200).json({ message: 'comments received' });
    } else {
        res.status(200).json({ message: 'comments is empty' });
    }
});

// POST 路径，用于接收 core_data 数据并推送到客户端
app.post('/api/core_data', (req, res) => {
    lastRequestTime = Date.now(); // 更新最近请求时间

    const data = req.body.data;
    const coreData = data?.core_data;
    const gmv = data?.pay_amt?.value;

    sendDataToClients({ gmv });

    if (Array.isArray(coreData)) {
        const formattedCoreData = coreData.map(item => {
            const indexDisplay = item?.index_display;
            const indexName = item?.index_name;
            const value = item?.value?.value;
            const unit = item?.value?.unit;
            return { indexDisplay, indexName, value, unit };
        });

        sendDataToClients({ core_data: formattedCoreData });
    } else {
        console.log('No core_data found or core_data is not an array.');
    }

    res.status(200).json({ message: 'Core data extracted and sent to clients.' });
});

// 提供评论数据的 API
app.get('/comments', (req, res) => {
    res.json(all_comments);
});

// 提供获取局域网IP的接口
app.get('/local-ip', (req, res) => {
    const ipAddress = getLocalIPAddress();
    if (ipAddress) {
        res.json({ ip: ipAddress });
    } else {
        res.status(404).json({ message: '未找到本地IP地址' });
    }
});

// 提供根路径（/）时返回 index.html
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

app.server = app.listen(port, () => {
    console.log(`Server is running at http://${getLocalIPAddress()}:${port}`);
});

app.server.on('upgrade', (request, socket, head) => {
    wss.handleUpgrade(request, socket, head, (ws) => {
        wss.emit('connection', ws, request);
    });
});
